//
//  MYShowViewController.m
//  faceLooker
//
//  Created by yww on 2018/12/26.
//  Copyright © 2018年 yww. All rights reserved.
//

#import "MYShowViewController.h"
#import "UIDevice+TFDevice.h"
#import "AppDelegate.h"
#import "FLOpenCVTool.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "MPTextView.h"

//定义图片种类
typedef NS_ENUM(NSUInteger, ImageType) {
    ImageTypeUnknow = 0,
    ImageTypeJPEG,
    ImageTypeJPEG2000,
    ImageTypeTIFF,
    ImageTypeBMP,
    ImageTypeICO,
    ImageTypeICNS,
    ImageTypeGIF,
    ImageTypePNG,
    ImageTypeWebP,
    ImageTypeOther,
};

typedef NS_ENUM (NSInteger , FLSelecteType)
{
    FLSelecteTypeRunText = 0,
    FLSelecteTypeRecText,
    FLSelecteTypeFLook,
    FLSelecteTypeImageFilter
};
typedef NS_ENUM (NSInteger , FLFaceAnsysType)
{
    FLFaceAnsysTypeExpression = 0,//表情
    FLFaceAnsysTypeAge,//年龄
    FLFaceAnsysTypeGender,//性别
    FLFaceAnsysTypeFaceValue//颜值
};
@interface MYShowViewController ()<UIImagePickerControllerDelegate>{
    MPTextView *inputTextView;
    UILabel *titleLabel;
    UIButton *showBtn;//跑马灯
    UIButton *recTextBtn;//印刷文字
    UIButton *fLookBtn;//人脸识别
    UIButton *filterImageBtn;//图片过滤
    UIImage *filterImage;//图片
}
@property(nonatomic,assign)BOOL isShowing;
@property(nonatomic,strong)UIView *myShowView;
@property(nonatomic,strong)UIImageView *backgroundImageView;
@property(nonatomic,strong)UIImageView *filterImageView;
@property(nonatomic,strong)UIView *coverView;//遮盖
@property(nonatomic,assign)FLSelecteType selecteType;
CG_EXTERN ImageType ImageDetectType(CFDataRef data);

@end
 

@implementation MYShowViewController
#pragma mark - 懒加载
- (UIImageView *)filterImageView{
    if (!_filterImageView) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 40, ScreenWidth-40, ScreenHeight-100)];
        imageView.clipsToBounds = YES;
        imageView.layer.cornerRadius = 5;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(filetImageLongTap:)];
        [imageView addGestureRecognizer:longTap];
        imageView.userInteractionEnabled = YES;
        _filterImageView = imageView;
    }
    return _filterImageView;
}

- (UIView *)coverView{
    if (!_coverView) {
        _coverView = [[UIView alloc]initWithFrame:self.view.frame];
        _coverView.backgroundColor =RGBACOLOR(130, 130, 130, 0.9);
    }
    return _coverView;
}

- (UIView *)myShowView{
    if (!_myShowView) {
        _myShowView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _myShowView.backgroundColor = [UIColor blackColor];
        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longTap:)];
        [_myShowView addGestureRecognizer:longTap];
    }
    return _myShowView;
}
- (UIImageView *)backgroundImageView{
    if (!_backgroundImageView) {
        _backgroundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _backgroundImageView.image = [UIImage imageNamed:@"bg2.jpg"];
        _backgroundImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageTapGesture:)];
        [_backgroundImageView addGestureRecognizer:tapGesture];
    }
    return _backgroundImageView;
}
- (AutoScrollLabel *)myShowLabel{
    if (!_myShowLabel) {
        _myShowLabel = [[AutoScrollLabel alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _myShowLabel.scrollSpeed = 150;//速度
        _myShowLabel.pauseInterval = 1.0;//暂停时间
        _myShowLabel.textColor = [UIColor whiteColor];
    }
    return _myShowLabel;
}

#pragma mark - 控制器方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self prefersStatusBarHidden];
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backgroundImageView];
    
   
    //注册通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationDidEnterBackground:) name:@"applicationDidEnterBackground" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillEnterForeground:) name:@"applicationWillEnterForeground" object:nil];
    //UI
    [self setupView];
}

//为image添加水波动画
- (void)addImageAnimation{
    [self.backgroundImageView.layer removeAllAnimations];
    
    CATransition *transition = [CATransition animation];
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    transition.duration = 1.5f;
    transition.type = @"rippleEffect"; // 指定动画类型
    transition.subtype = @"fromLeft"; // 指定过渡方向
    // 设置开始和结束的进度，范围都是0.0-1.0
    transition.startProgress = 0.2f;
    transition.endProgress = 1.0f;
    [self.backgroundImageView.layer addAnimation:transition forKey:@"imageWave"];
    
    /*
     fade                   //交叉淡化过渡(不支持过渡方向) 淡入
     push                   //新视图把旧视图推出去 推送出去
     moveIn                 //新视图移到旧视图上面 移动视图
     reveal                 //将旧视图移开,显示下面的新视图
     cube                   //立方体翻滚效果
     oglFlip                //上下左右翻转效果
     suckEffect             //收缩效果，向布被抽走(不支持过渡方向)
     rippleEffect           //水波效果(不支持过渡方向)
     pageCurl               //向上翻页效果
     pageUnCurl             //向下翻页效果
     cameraIrisHollowOpen   //相机镜头打开效果(不支持过渡方向)
     cameraIrisHollowClose  //相机镜头关上效果(不支持过渡方向)
     */
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
     
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"applicationDidEnterBackground" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"applicationWillEnterForeground" object:nil];
}


- (void)setupView{
    //标题
    titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 30, ScreenWidth -20, 20)];
    titleLabel.textColor = [UIColor darkGrayColor];
    titleLabel.text = @"内容";
    titleLabel.font = Font(16);
    [self.backgroundImageView addSubview:titleLabel];
    
    //鱼跃背景
    KYWaterWaveView *fashView = [[KYWaterWaveView alloc] initWithFrame:CGRectMake(10, 60, ScreenWidth -20, 100)];
//    fashView.backgroundColor = RGBACOLOR(213, 57, 74, 0.5);
    fashView.depthCoefficient = 1.3;//深度系数
    fashView.waveColor = randomColor;
    fashView.layer.cornerRadius = 10;
    fashView.clipsToBounds = YES;
    fashView.waveSpeed = 6.0f;//波浪速度
    fashView.waveAmplitude = 6.0f;//波浪振幅
    [self.backgroundImageView addSubview:fashView];
    [fashView wave];
    
    //内容
    inputTextView = [[MPTextView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth -20, 100)];
    inputTextView.textColor = [UIColor redColor];
    inputTextView.placeholderText = @"请输入你的内容...";
    inputTextView.font = Font(16);
    inputTextView.textAlignment = NSTextAlignmentLeft;
    inputTextView.backgroundColor = [UIColor clearColor];
    inputTextView.layer.cornerRadius = 10;
    inputTextView.clipsToBounds = YES;
    inputTextView.layer.borderWidth = 1;
    inputTextView.layer.borderColor = [UIColor darkGrayColor].CGColor;
    [fashView addSubview:inputTextView];
    
    //人脸信息
    fLookBtn  = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-90, 1.57*ScreenHeight/3.0, 40, 40)];
    fLookBtn.backgroundColor = RGBACOLOR(104, 197, 210, 0.5);
    fLookBtn.layer.cornerRadius = 20;
    fLookBtn.clipsToBounds = YES;
    fLookBtn.layer.borderWidth = 1;
    fLookBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    fLookBtn.titleLabel.font = Font(20);
    [fLookBtn setTitle:@"脸" forState:UIControlStateNormal];
    [fLookBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [fLookBtn addTarget:self action:@selector(fLookBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundImageView addSubview:fLookBtn];
    
    //文字识别
    recTextBtn  = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-120,  1.2*ScreenHeight/3.0, 54, 54)];
//    recTextBtn  = [[UIButton alloc]initWithFrame:CGRectMake( ScreenWidth-90, 1.57*ScreenHeight/3.0, 54, 54)];
    recTextBtn.backgroundColor = RGBACOLOR(221, 168, 206, 0.5);
    recTextBtn.layer.cornerRadius = 27;
    recTextBtn.clipsToBounds = YES;
    recTextBtn.layer.borderWidth = 1;
    recTextBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    recTextBtn.titleLabel.font = Font(20);
    [recTextBtn setTitle:@"文" forState:UIControlStateNormal];
    [recTextBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [recTextBtn addTarget:self action:@selector(recTextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundImageView addSubview:recTextBtn];
    
    //跑马灯按钮
    showBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-80, 170, 70, 70)];
//    showBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-90, 1.57*ScreenHeight/3.0, 70, 70)];
    showBtn.backgroundColor = RGBACOLOR(213, 57, 74, 0.5);
    showBtn.layer.cornerRadius = 35;
    showBtn.clipsToBounds = YES;
    showBtn.layer.borderWidth = 1;
    showBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    showBtn.titleLabel.font = Font(20);
    [showBtn setTitle:@"跑" forState:UIControlStateNormal];
    [showBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [showBtn addTarget:self action:@selector(showBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundImageView addSubview:showBtn];
    
    //图片过滤
    filterImageBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-190, 200, 60, 60)];
    //showBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-90, 1.57*ScreenHeight/3.0, 70, 70)];
    filterImageBtn.backgroundColor = RGBACOLOR(145, 169, 203, 0.5);
    filterImageBtn.layer.cornerRadius = 30;
    filterImageBtn.clipsToBounds = YES;
    filterImageBtn.layer.borderWidth = 1;
    filterImageBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    filterImageBtn.titleLabel.font = Font(20);
    [filterImageBtn setTitle:@"滤" forState:UIControlStateNormal];
    [filterImageBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [filterImageBtn addTarget:self action:@selector(filterImageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundImageView addSubview:filterImageBtn];
    
    //清空
    UIButton *clearTextBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-70, 25,60, 30)];
    clearTextBtn.backgroundColor = [UIColor clearColor];
    [clearTextBtn setTitle:@"清空" forState:UIControlStateNormal];
    clearTextBtn.titleLabel.font = Font(16);
    [clearTextBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [clearTextBtn addTarget:self action:@selector(clearTextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundImageView addSubview:clearTextBtn];
}
#pragma mark - 通知 手势 按钮
- (void)imageTapGesture:(UIGestureRecognizer *)gesture{
    if (self.isShowing) {
        return;
    }
    [inputTextView resignFirstResponder];
    [self addImageAnimation];
    NSLog(@"水波");
}

- (void)applicationWillEnterForeground:(NSNotification *)notice{
    NSLog(@"进入前台");
    if (self.isShowing) {
        //开启定时器
        [self.myShowLabel scroll];
    }
}
- (void)applicationDidEnterBackground:(NSNotification *)notice{
    //关闭定时器
    NSLog(@"进入后台");
}
- (void)clearTextBtnClick:(UIButton*)btn{
    NSLog(@"清空");
    inputTextView.text = @"";
}
- (void)filterImageBtnClick:(UIButton *)btn{
    NSLog(@"图片过滤");
    self.selecteType = FLSelecteTypeImageFilter;
    //弹框选择
    [self openSystemActionSheet];
}

- (void)recTextBtnClick:(UIButton *)btn{
    NSLog(@"文字识别");
    if ([FLGlobalTool sharedInstance].networkStatus <= 0) {
        [MBProgressHUD showError:@"网络出现错误" toView:self.view];
        return;
    }
    self.selecteType = FLSelecteTypeRecText;
    //弹框选择
    [self openSystemActionSheet];
}
- (void)fLookBtnClick:(UIButton *)btn{
    NSLog(@"人脸信息");
    if ([FLGlobalTool sharedInstance].networkStatus <= 0) {
        [MBProgressHUD showError:@"网络出现错误" toView:self.view];
        return;
    }
    self.selecteType = FLSelecteTypeFLook;
    [self openSystemActionSheet]; //弹框选择
}
- (void)showBtnClick:(UIButton *)btn{
    [inputTextView resignFirstResponder];
    self.selecteType = FLSelecteTypeRunText;
    //去空格
    NSString *str = [self  removeSpaceAndNewline:inputTextView.text];
    NSLog(@"内容为：%@ 长度==%zd", str,str.length);
    if (str.length >0 ) {
        if (str.length > 130) {
            [MBProgressHUD showError:@"最多展示130个文字" toView:self.view];
            return;
        }
        //允许转成横屏
        AppDelegate * appDelegate =  (AppDelegate*)[UIApplication sharedApplication].delegate;
        appDelegate.allowRotation= YES;
        //调用横屏代码
        [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeLeft];
        self.isShowing = YES;
        WeakSelf
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //添加视图
            if (ScreenWidth < ScreenHeight) {
                NSLog(@"不好不好 屏幕没转screenW = %f,screenH = %f",ScreenWidth,ScreenHeight);
                if (IS_PAD) {
                    if (str.length > 20) {
                        [MBProgressHUD showError:@"最多展示20个文字" toView:self.view];
                        return;
                    }
                }
                weakSelf.myShowLabel.font = [UIFont boldSystemFontOfSize:ScreenWidth-20];
            }else{
                weakSelf.myShowLabel.font = [UIFont boldSystemFontOfSize:ScreenHeight-40];
            }
            weakSelf.myShowLabel.text = str;
            [weakSelf.myShowView addSubview:weakSelf.myShowLabel];
            [weakSelf.backgroundImageView addSubview:weakSelf.myShowView];
        });
        
    }else{
        [MBProgressHUD showError:@"请输入内容" toView:self.view];
    }
}

//去除字符串首尾的空格和换行符
- (NSString*)removeSpaceAndNewline:(NSString *)str {
    if (str.length > 0) {
        str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
        str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    }
    return str;
}

- (void)longTap:(UIGestureRecognizer *)tap{
    NSLog(@"长按");
    //允许转成横屏
    AppDelegate * appDelegate =  (AppDelegate*)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation= NO;
    //调用横屏代码
    [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
    self.isShowing = NO;
    WeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.myShowLabel removeFromSuperview];
        weakSelf.myShowLabel = nil;
        [weakSelf.myShowView removeFromSuperview];
    });
}
- (void)cancelBtnClick:(UIButton *)btn{
    [self.coverView removeFromSuperview];
    self.coverView = nil;
    self.filterImageView = nil;
    filterImage = nil;
}
- (void)fiterBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected) {
        UIImage *newImage;
        switch (btn.tag) {
            case 0:
                NSLog(@"方框滤波");
                newImage = [[FLOpenCVTool sharedInstance] ImageToBoxFilter:filterImage];
                break;
            case 1:
                NSLog(@"高斯滤波");
                newImage = [[FLOpenCVTool sharedInstance] ImageToGaussianBlur:filterImage];
                break;
            case 2:
                NSLog(@"中值滤波");
                newImage = [[FLOpenCVTool sharedInstance] ImageToMedianFilter:filterImage];
                break;
            case 3:
                NSLog(@"双边滤波");
                newImage = [[FLOpenCVTool sharedInstance] ImageTobilateraFilter:filterImage];
                break;
            case 4:
                NSLog(@"均值滤波");
                newImage = [[FLOpenCVTool sharedInstance] ImageToblurFilter:filterImage];
                break;
            default:
                break;
        }
        NSLog(@"设置1");
        self.filterImageView.image = newImage;
    }else{
        NSLog(@"设置2");
        self.filterImageView.image = filterImage;
    }
    [self setCoverViewSubViews:btn.tag];//设定按钮状态
}

- (void)setCoverViewSubViews:(NSInteger)tag{
    for (UIView *subView in self.coverView.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)subView;
            if (btn.tag == tag) {
                if (btn.selected) {
                    btn.backgroundColor = RGBACOLOR(208, 111, 75, 0.8);
                }else{
                    btn.selected = NO;
                    btn.backgroundColor  =[UIColor clearColor];
                }
            }else{
                 btn.selected = NO;
                btn.backgroundColor  =[UIColor clearColor];
            }
            
        }
    }
    
}
- (void)filetImageLongTap:(UIGestureRecognizer *)gesture{
    NSLog(@"保存图片");
    WeakSelf
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"保存图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        
    }];
    
    UIAlertAction *save = [UIAlertAction actionWithTitle:@"保存到相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImage *saveImage = weakSelf.filterImageView.image;
        __block ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
        [lib writeImageToSavedPhotosAlbum:[saveImage CGImage] orientation:(ALAssetOrientation)saveImage.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
            if (error) {//
                [MBProgressHUD showError:@"保存失败" toView:weakSelf.view];
            }else{
                [MBProgressHUD showError:@"图片已保存到相册" toView:weakSelf.view];
            }
        }];
    }];
    
    [alertVc addAction:cancle];
    [alertVc addAction:save];
    [self presentViewController:alertVc animated:YES completion:nil];
    if (IS_PAD) {
        UIPopoverPresentationController *popover = alertVc.popoverPresentationController;
        if (popover) {
            popover.sourceView = [UIApplication sharedApplication].keyWindow.rootViewController.view;
            popover.sourceRect =  CGRectMake(ScreenWidth/2.0,ScreenHeight,1.0,1.0);
            popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
        }
    }
}

#pragma mark - 相册 相机 UIImagePickerControllerDelegate
//调用ActionSheet
- (void)openSystemActionSheet{
    if ([FLGlobalTool sharedInstance].networkStatus <= 0) {
         [MBProgressHUD showError:@"请检查你的网络" toView:self.view];
        return;
    }
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        NSLog(@"取消");
    }];

    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = (id)self;
        imagePicker.allowsEditing = YES;
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *picture = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        pickerImage.allowsEditing = YES;
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = (id)self;
        pickerImage.allowsEditing = NO;
        [self presentViewController:pickerImage animated:YES completion:nil];
    }];
    
    [alertVc addAction:cancle];
    [alertVc addAction:camera];
    [alertVc addAction:picture];
    [self presentViewController:alertVc animated:YES completion:nil];
    
    if (IS_PAD) {
        UIPopoverPresentationController *popover = alertVc.popoverPresentationController;
        if (popover) {
            popover.sourceView = [UIApplication sharedApplication].keyWindow.rootViewController.view;
            popover.sourceRect =  CGRectMake(ScreenWidth/2.0,ScreenHeight,1.0,1.0);
            popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
        }
    }
}

//pickerController的代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:NO completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    CGFloat fixelW = CGImageGetWidth(image.CGImage);
    CGFloat fixelH = CGImageGetHeight(image.CGImage);
    
    UIImage *newImage;
    if (self.selecteType == FLSelecteTypeRecText) {//文字识别
        CGFloat scaleX = fixelW/800;
        CGFloat scaleY = fixelH/800;
        CGFloat scale = 1.0;
        if (scaleX >= scaleY && scaleX >1.0) {
            scale = scaleX;
        }else if(scaleX < scaleY && scaleY>1.0){
            scale = scaleY;
        }
        newImage=[self scaleImage:image toScale:1/scale];
        NSData *imageData = UIImageJPEGRepresentation(newImage, 1.0);
        NSString *encodedImageStr = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
// NSString *imageDecodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,(__bridge CFStringRef)encodedImageStr,CFSTR(""),CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
        [self printTextRecognize:encodedImageStr ];//文字

    }else if (self.selecteType == FLSelecteTypeImageFilter){//图片滤镜
        [self setImageFilterView:image];
        
    }else if (self.selecteType == FLSelecteTypeFLook){//人脸熟悉
        CGFloat scaleX = fixelW/2048;
        CGFloat scaleY = fixelH/2048;
        CGFloat scale = 1.0;
        if (scaleX >= scaleY && scaleX>1.0) {
            scale = scaleX;
        }else if(scaleX < scaleY && scaleY>1.0){
            scale = scaleY;
        }
        newImage=[self scaleImage:image toScale:1/scale];
        [self openFaceActionSheet:newImage];
    }
}

//文字识别
- (void)printTextRecognize:(NSString *)str{
//    NSString *ip =[FLHttpCommunicate  getIPAddress:YES];
//    NSLog(@"ip ========== %@",ip);
    NSDictionary *headerDic =  @{@"Content-Type": @"application/x-www-form-urlencoded; charset=utf-8"};
    NSDictionary *parameters = @{
                                  @"api_key": ks_apikey,
                                  @"api_secret":ks_apiSecret,
                                  @"image_base64":str
                                };
    NSString *host = @"https://api-cn.faceplusplus.com/imagepp/v1/recognizetext";
    [MBProgressHUD wj_showActivityLoading:@"识别中..." toView:self.view];
    [FLHttpCommunicate POST:host header:headerDic parameters:parameters timeOut:HTTP_TIME_NETOUT dictBlock:^(NSDictionary *dict) {
        NSLog(@"文字识别结果==%@",dict);
        NSArray *result = dict[@"result"];
        [MBProgressHUD wj_hideHUDForView:self.view];
        NSMutableString *resultStr = [NSMutableString string];
        if (result.count > 0) {
            for ( NSDictionary *resultDic in result) {
                NSString *strs = resultDic[@"value"];
                [resultStr appendFormat:@"%@", strs];
            }
            if (resultStr.length == 0) {
                [MBProgressHUD showError:@"未识别任何文字" toView:self.view];
            }else{
                //展示
                NSLog(@"文字--------%@",resultStr);
                self->inputTextView.text = resultStr;
            }
        }else{
           [MBProgressHUD wj_hideHUDForView:self.view];
           [MBProgressHUD showError:@"未识别任何文字" toView:self.view];
        }
        
    } errorBlock:^(NSError *error) {
        NSLog(@"error == %@",error);
        [MBProgressHUD wj_hideHUDForView:self.view];
        [MBProgressHUD showError:@"未识别任何文字" toView:self.view];
    }];
    
}
#pragma mark - 人脸识别选择
//调用ActionSheet
- (void)openFaceActionSheet:(UIImage *)image{
    WeakSelf
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"人脸分析" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
    }];
    
    UIAlertAction *expression = [UIAlertAction actionWithTitle:@"表情" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf getValueWith:image faceAnsysType:FLFaceAnsysTypeExpression];
    }];
    
    UIAlertAction *age = [UIAlertAction actionWithTitle:@"年龄" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf getValueWith:image faceAnsysType:FLFaceAnsysTypeAge];
        
    }];
    
    UIAlertAction *gender = [UIAlertAction actionWithTitle:@"性别" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf getValueWith:image faceAnsysType:FLFaceAnsysTypeGender];
        
    }];
    
    UIAlertAction *faceValue = [UIAlertAction actionWithTitle:@"颜值" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        [weakSelf getValueWith:image faceAnsysType:FLFaceAnsysTypeFaceValue];
    }];
    
    [alertVc addAction:cancle];
    [alertVc addAction:faceValue];
    [alertVc addAction:gender];
    [alertVc addAction:age];
    [alertVc addAction:expression];
    [self presentViewController:alertVc animated:YES completion:nil];
    
    if (IS_PAD) {
        UIPopoverPresentationController *popover = alertVc.popoverPresentationController;
        if (popover) {
            popover.sourceView = [UIApplication sharedApplication].keyWindow.rootViewController.view;
            popover.sourceRect =  CGRectMake(ScreenWidth/2.0,ScreenHeight,1.0,1.0);
            popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
        }
    }
}
//获取人脸分析
- (void)getValueWith:(UIImage *)image faceAnsysType:(FLFaceAnsysType)faceAnsysType{
    NSData *imageDada = UIImageJPEGRepresentation(image, 1.0);
    if (imageDada.length >4*1024*1024) {//大于4M不被允许
        [MBProgressHUD showError:@"图片过大" toView:self.view];
        return;
    }
    NSString *encodedImageStr = [imageDada base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    //图片种类判断
    NSString *nameType;
    ImageType imageType = ImageDetectType((__bridge CFDataRef)imageDada);
    if (imageType == ImageTypeJPEG) {
        nameType = @"jpeg";
    }else if (imageType == ImageTypeBMP){
        nameType = @"bmp";
    }else if (imageType == ImageTypePNG){
        nameType = @"png";
    }else{
        [MBProgressHUD showError:@"文件格式不支持" toView:self.view];
        return;
    }
    NSDictionary *headerDic =  @{@"Content-Type": @"application/x-www-form-urlencoded; charset=utf-8"
                                 };
    NSString *return_attributes;
    if (faceAnsysType == FLFaceAnsysTypeExpression) {
        return_attributes = @"emotion";
    }else if (faceAnsysType == FLFaceAnsysTypeAge){
        return_attributes = @"age";
    }else if (faceAnsysType == FLFaceAnsysTypeGender){
        return_attributes = @"gender";
    }else{
        return_attributes = @"beauty";
    }
    
    NSString *host = @"https://api-cn.faceplusplus.com/facepp/v3/detect";
    NSDictionary *parameters = @{
                                 @"api_key": ks_apikey,
                                 @"api_secret":ks_apiSecret,
                                 @"image_base64":encodedImageStr,
                                 @"return_attributes":return_attributes
                                 };
    
    [MBProgressHUD wj_showActivityLoading:@"识别中..." toView:self.view];
    [FLHttpCommunicate POST:host headers:headerDic fileData:imageDada imageType:nameType parameters:parameters timeOut:HTTP_TIME_NETOUT dictBlock:^(NSDictionary *dict) {
        NSLog(@"人脸识别结果==%@",dict);
        NSArray *faces = dict[@"faces"];
        [MBProgressHUD wj_hideHUDForView:self.view];
        
        if (faces.count > 0) {
            NSString *message = @"";
            if (faceAnsysType == FLFaceAnsysTypeExpression) {
                //展示表情
                NSLog(@"-------表情-------");
                NSMutableString *valueM =[NSMutableString string];
                for (NSDictionary *faceDic in faces) {
                    NSDictionary *attributesDic = faceDic[@"attributes"];
                    NSDictionary *emotionDic = attributesDic[return_attributes];
                    //判断表情
                    [valueM appendFormat:@"%@ ",[self getEmotion:emotionDic]];
                }
                message = [NSString stringWithFormat:@"表情分别为：%@",valueM];
        
            }else if (faceAnsysType == FLFaceAnsysTypeAge){
                //展示表情
                NSLog(@"-------年龄-------");
                NSMutableString *valueM =[NSMutableString string];
                for (NSDictionary *faceDic in faces) {
                    NSDictionary *attributesDic = faceDic[@"attributes"];
                    NSDictionary *ageDic = attributesDic[return_attributes];
                    NSString *value = ageDic [@"value"];
                    if (!value) {
                        value = @"xx";
                    }
                    [valueM appendFormat:@"%@岁 ",value];
                }
                message = [NSString stringWithFormat:@"年龄分别为：%@",valueM];
                
            }else if (faceAnsysType == FLFaceAnsysTypeGender){
                //展示表情
                NSLog(@"-------性别-------");
                NSMutableString *valueM =[NSMutableString string];
                for (NSDictionary *faceDic in faces) {
                    NSDictionary *attributesDic = faceDic[@"attributes"];
                    NSDictionary *genderDic = attributesDic[return_attributes];
                    NSString *value =genderDic [@"value"];
                    if ([value isEqualToString:@"Male"]) {
                        [valueM appendFormat:@"男性 "];
                    }else{
                        [valueM appendFormat:@"女性 "];
                    }
                }
                message = [NSString stringWithFormat:@"分别为：%@",valueM];
                
            }else if (faceAnsysType == FLFaceAnsysTypeFaceValue){
                //展示表情
                NSLog(@"-------颜值-------");
                NSMutableString *female_value =[NSMutableString string];
                NSMutableString *male_value =[NSMutableString string];
                for (NSDictionary *faceDic in faces) {
                    NSDictionary *attributesDic = faceDic[@"attributes"];
                    NSDictionary *beautyDic = attributesDic[return_attributes];
                    NSString *female_score =beautyDic [@"female_score"];
                    NSString *male_score =beautyDic [@"male_score"];
                    if (!female_score) {
                        female_score = @"0.0";
                    }
                    if (!male_score) {
                        male_score = @"0.0";
                    }
                    [female_value appendFormat:@"%.1f分 ",[female_score floatValue]];
                    [male_value appendFormat:@"%.1f分 ",[male_score floatValue]];
                }
                message = [NSString stringWithFormat:@"男性认为颜值分别为：%@\n女性认为颜值分别为：%@",male_value,female_value];
            }
            [self showResultMessage:message image:image faceAnsysType:faceAnsysType];
        }else{
            [MBProgressHUD wj_hideHUDForView:self.view];
            [MBProgressHUD showError:@"无法识别" toView:self.view];
        }
    } errorBlock:^(NSError *error) {
        NSLog(@"error == %@",error);
        [MBProgressHUD wj_hideHUDForView:self.view];
        [MBProgressHUD showError:@"发生意外，无法提供服务" toView:self.view];
    }];
    
}
#pragma mark - 私有方法
- (void)setImageFilterView:(UIImage *)image{
    [self.backgroundImageView addSubview:self.coverView];
    //添加图片
    filterImage = image;
    self.filterImageView.image = filterImage;
    [self.coverView addSubview:self.filterImageView];
    //撤销按钮
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-50, 0, 40, 40)];
    cancelBtn.layer.cornerRadius = 20;
    cancelBtn.clipsToBounds = YES;
    cancelBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cancelBtn.layer.borderWidth = 1.0;
    
    cancelBtn.backgroundColor = [UIColor clearColor];
    [cancelBtn setTitle:@"X" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = Font(25);
    [cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.coverView addSubview:cancelBtn];
    //过滤按钮
    CGFloat width = 45.0;
    CGFloat magin = ((ScreenWidth-20)/5.0-45)/2.0;
    NSArray *titleArr = @[@"方框",@"高斯",@"中值",@"双边",@"均值"];
    for (int i = 0; i < 5; i++) {
        UIButton *fiterBtn = [[UIButton alloc]initWithFrame:CGRectMake(10+magin+i*(ScreenWidth-20)/5.0, ScreenHeight-50, width , 30)];
        fiterBtn.tag = i;
        fiterBtn.titleLabel.font = Font(16);
        fiterBtn.layer.borderWidth = 1.0;
        fiterBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        [fiterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [fiterBtn setTitle:titleArr[i] forState:UIControlStateNormal];
        [fiterBtn addTarget:self action:@selector(fiterBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        fiterBtn.backgroundColor = [UIColor clearColor];
        [self.coverView addSubview:fiterBtn];
    }
    
}
- (NSString *)getEmotion:(NSDictionary *)emotionDic{
    float value = 0.0;
    NSString *result;
    NSArray *translateArr = @[@"生气",@"反感",@"恐惧",@"开心",@"自然",@"伤心",@"惊讶"];//表情包
    float anger = [emotionDic[@"anger"] floatValue];
    float disgust = [emotionDic[@"disgust"] floatValue];
    float fear = [emotionDic[@"fear"] floatValue];
    float happiness = [emotionDic[@"happiness"] floatValue];
    float neutral = [emotionDic[@"neutral"] floatValue];
    float sadness = [emotionDic[@"sadness"] floatValue];
    float surprise = [emotionDic[@"surprise"] floatValue];
    NSArray *reasultValueArr = @[@(anger),@(disgust),@(fear),@(happiness),@(neutral),@(sadness),@(surprise)];
    for (NSInteger i = 0; i <6; i++) {
        NSNumber *num = reasultValueArr[i];
        if (num.floatValue >= value) {
            value = num.floatValue;
            result =translateArr[i];
        }
    }
    if (result.length == 0) {
        result = @"未知";
    }
    return result;
    
}
- (void)showResultMessage:(NSString *)message  image:(UIImage *)image faceAnsysType:(FLFaceAnsysType)faceAnsysType{
    [self.backgroundImageView addSubview:self.coverView];//添加背景
    //添加图片
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, ScreenWidth-100, ScreenHeight/3.0)];
    imageView.image = image;
    imageView.clipsToBounds = YES;
    imageView.layer.cornerRadius = 5;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.coverView addSubview:imageView];
    //撤销按钮
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-50, 10, 40, 40)];
    cancelBtn.layer.cornerRadius = 20;
    cancelBtn.clipsToBounds = YES;
    cancelBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cancelBtn.layer.borderWidth = 1.0;
    cancelBtn.backgroundColor = [UIColor clearColor];
    [cancelBtn setTitle:@"X" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = Font(25);
    [cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.coverView addSubview:cancelBtn];
    //展示
    CGFloat height = [self getLabelHeightWithText:message width:ScreenWidth-2 font:16];
    UILabel *showLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, ScreenHeight/3.0+50, ScreenWidth-20, height+10)];
    showLabel.backgroundColor = [UIColor clearColor];
    showLabel.font = Font(16);
    showLabel.numberOfLines = 0;
    showLabel.textColor = [UIColor lightGrayColor];
    showLabel.textAlignment = NSTextAlignmentLeft;
 
    showLabel.text = message;
    [self.coverView addSubview:showLabel];
    
    
    
}

//根据宽度求高度 包含换行  content 计算的内容  width 计算的宽度 font字体大小
- (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width font: (CGFloat)font{
//    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSDictionary * attributes = @{
                                  NSFontAttributeName:[UIFont systemFontOfSize:font],
                                  NSParagraphStyleAttributeName: paragraphStyle
                                  };
    CGSize textRect = CGSizeMake(width, MAXFLOAT);
    CGFloat textHeight = [text boundingRectWithSize: textRect
                                           options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                        attributes:attributes
                                           context:nil].size.height;
    return textHeight;
}

//md5转化加密
- (NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
    
}

//获取当前时间转为时间戳
- (NSString *)dateTransformToTimeSp{
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970];//客户端当前10位毫秒级时间戳
    NSString *timeSp = [NSString stringWithFormat:@"%llu",recordTime];//时间戳转字符串(10位毫秒级时间戳字符串)
    return timeSp;
}
/*
 */

/**
 图片尺寸裁剪
 
 @param image 图片
 @param newSize 新的大小
 @return 返回数据
 */
- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 1.0);
}
//等比例缩放
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
#pragma mark - 存取图片
- (void)saveImage:(UIImage *)image {
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:
                          [NSString stringWithFormat:@"myimage.jpg"]];  // 保存文件的名称
    
    BOOL result =[UIImagePNGRepresentation(image)writeToFile:filePath   atomically:YES]; // 保存成功会返回YES
    if (result == YES) {
        NSLog(@"保存成功");
    }
    
}

- (UIImage *)getImage {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:
                          [NSString stringWithFormat:@"myimage.jpg"]];
    // 保存文件的名称
    UIImage *img = [UIImage imageWithContentsOfFile:filePath];
    return img;
}
//示例：删除沙盒中所有文件或数据库
-(void)deleteDocuments{
    NSString *path = [NSString stringWithFormat:@"/Documents"];
    NSString *fieldPathss=[NSHomeDirectory() stringByAppendingString:path];
    NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fieldPathss error:nil];
    NSString *filePath = nil;
    NSError *error = nil;
    for (NSString *subPath in subPathArr){
        filePath = [fieldPathss stringByAppendingPathComponent:subPath];
        //删除子文件夹
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (error) {
            NSLog(@"清空沙盒失败");
        }
    }
}
//图片种类判断
ImageType ImageDetectType(CFDataRef data){
    if (!data) return ImageTypeUnknow;
    uint64_t length = CFDataGetLength(data);
    if (length < 16) return ImageTypeUnknow;
    
    const char *bytes = (char *)CFDataGetBytePtr(data);
    uint32_t magic4 = *((uint32_t *)bytes);
    switch (magic4) {
        case _FOUR_CC(0x4D, 0x4D, 0x00, 0x2A): { // big endian TIFF
            return ImageTypeTIFF;
        } break;
            
        case _FOUR_CC(0x49, 0x49, 0x2A, 0x00): { // little endian TIFF
            return ImageTypeTIFF;
        } break;
            
        case _FOUR_CC(0x00, 0x00, 0x01, 0x00): { // ICO
            return ImageTypeICO;
        } break;
            
        case _FOUR_CC('i', 'c', 'n', 's'): { // ICNS
            return ImageTypeICNS;
        } break;
            
        case _FOUR_CC('G', 'I', 'F', '8'): { // GIF
            return ImageTypeGIF;
        } break;
            
        case _FOUR_CC(0x89, 'P', 'N', 'G'): {  // PNG
            uint32_t tmp = *((uint32_t *)(bytes + 4));
            if (tmp == _FOUR_CC('\r', '\n', 0x1A, '\n')) {
                return ImageTypePNG;
            }
        } break;
            
        case _FOUR_CC('R', 'I', 'F', 'F'): { // WebP
            uint32_t tmp = *((uint32_t *)(bytes + 8));
            if (tmp == _FOUR_CC('W', 'E', 'B', 'P')) {
                return ImageTypeWebP;
            }
        } break;
    }
    
    uint16_t magic2 = *((uint16_t *)bytes);
    switch (magic2) {
        case _TWO_CC('B', 'A'):
        case _TWO_CC('B', 'M'):
        case _TWO_CC('I', 'C'):
        case _TWO_CC('P', 'I'):
        case _TWO_CC('C', 'I'):
        case _TWO_CC('C', 'P'): { // BMP
            return ImageTypeBMP;
        }
            
        case _TWO_CC(0xFF, 0x4F): { // JPEG2000
            return ImageTypeJPEG2000;
        }
            
    }
    if (memcmp(bytes,"\377\330\377",3) == 0) return ImageTypeJPEG;
    if (memcmp(bytes + 4, "\152\120\040\040\015", 5) == 0) return ImageTypeJPEG2000;
    return ImageTypeUnknow;
}
#pragma mark - 动画
-(CAAnimationGroup *)move:(float)time X:(NSNumber *)x Y:(NSNumber *)y{
    /* 动画1（在X轴方向移动） */
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    // 终点设定
    animation1.toValue = x;; // 終点
    /* 动画1（在X轴方向移动） */
    CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    // 终点设定
    animation2.toValue = y;; // 終点
    /* 动画组 */
    CAAnimationGroup *group = [CAAnimationGroup animation];
    // 动画选项设定
    group.duration = time;
    group.repeatCount = MAXFLOAT;
    // 添加动画
    group.animations = [NSArray arrayWithObjects:animation1, animation2, nil];
    
    return group;
}

 - (BOOL)prefersStatusBarHidden{
    return YES;//隐藏为YES，显示为NO
     /*
      如何隐藏状态栏
      */
}
@end
